﻿
@page "/Account/Login"
@layout LoginLayout

@using System.ComponentModel.DataAnnotations
@using Microsoft.AspNetCore.Authentication
@using Microsoft.AspNetCore.Identity
@using Identity.Data

@inject SignInManager<User> SignInManager
@inject ILogger<Login> Logger
@inject NavigationManager NavigationManager
@inject IdentityRedirectManager RedirectManager
 @rendermode InteractiveWebAssembly
<PageTitle>登录</PageTitle>

<div >
    <div >
        <div>
            <div>
                <div>
                    <h2 >欢迎回来</h2>
                </div>
                <div>
                    @if (!string.IsNullOrEmpty(errorMessage))
                    {
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <span>⚠️ @errorMessage</span>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    }

                 <EditForm Model="Input" method="post" OnValidSubmit="LoginUser" FormName="login">
                        <DataAnnotationsValidator />
                        <ValidationSummary class="alert alert-danger" />

                        <!-- 用户名输入 -->
                        <div class="mb-4">
                            <label for="Input.Username" class="form-label">用户名</label>
                            <InputText @bind-Value="Input.Username" id="Input.Username" class="form-control form-control-lg" placeholder="请输入用户名" />
                            <ValidationMessage For="() => Input.Username" class="text-danger small" />
                        </div>

                        <!-- 密码输入 -->
                        <div class="mb-4">
                            <label for="Input.Password" class="form-label">密码</label>
                            <InputText type="password" @bind-Value="Input.Password" id="Input.Password" class="form-control form-control-lg" placeholder="请输入密码" />
                            <ValidationMessage For="() => Input.Password" class="text-danger small" />
                        </div>

                        <!-- 记住我 -->
                        <div class="mb-4 form-check">
                            <InputCheckbox @bind-Value="Input.RememberMe" class="form-check-input" id="RememberMe" />
                            <label for="RememberMe" class="form-check-label">保持登录状态</label>
                        </div>

                        <!-- 登录按钮 -->
                        <div class="d-grid mb-4">
                            <button type="submit" class="btn btn-primary btn-lg">登录</button>
                        </div>
                    </EditForm>

                    <!-- 辅助链接 -->
         
                </div>
            </div>
        </div>
    </div>
</div>

@code {
    private string? errorMessage;

    [CascadingParameter]
    private HttpContext HttpContext { get; set; } = default!;

    [SupplyParameterFromForm]
    private InputModel Input { get; set; } = new();

    [SupplyParameterFromQuery]
    private string? ReturnUrl { get; set; }

    protected override async Task OnInitializedAsync()
    {
        if (HttpMethods.IsGet(HttpContext.Request.Method) && !HttpContext.User.Identity?.IsAuthenticated == true)
        {
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
        }
    }

    public async Task LoginUser()
    {
        var result = await SignInManager.PasswordSignInAsync(Input.Username, Input.Password, Input.RememberMe, lockoutOnFailure: false);
        if (result.Succeeded)
        {
            Logger.LogInformation("User logged in.");
            RedirectManager.RedirectTo(ReturnUrl);
        }
        else if (result.RequiresTwoFactor)
        {
            RedirectManager.RedirectTo(
                "Account/LoginWith2fa",
                new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe });
        }
        else if (result.IsLockedOut)
        {
            Logger.LogWarning("User account locked out.");
            RedirectManager.RedirectTo("Account/Lockout");
        }
        else
        {
            errorMessage = "Error: Invalid login attempt.";
        }
    }

    private sealed class InputModel
    {
        [Required]
        public string Username { get; set; } = "";

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; } = "";

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
    }
}
